<template>
    <div :class="`tech-commodity-detail ${mode}`">
        <!-- 轮播图 -->
        <Swiper :picList="goodsDetail ? goodsDetail.title_pics : []" />
        <!-- <CountDown :time="446143246" /> -->
        <!-- 基础信息 -->
        <BaseInfo :info="goodsDetail" />
        <ActivityInfo />
        <!-- 规格，地址 -->
        <SelectArea v-if="goodsDetail && goodsDetail.skus.length > 1" @selectSku="selectSku" />
        <!-- 店铺信息 -->
        <ShopDesc v-if="storeInfo" class="shop-info-container" :shopInfo="storeInfo" is-link />
        <!-- <template v-if="specialShopInfo">
        </template> -->
        <!-- 图文详情 -->
        <PictureAndText :desc="goodsDetail ? goodsDetail.detail_description : ''" :picList="goodsDetail ? goodsDetail.detail_pics : []" />
        <Footer :noBackground="true" :isHaveBar="true" />
        <DetailTip v-if="isDisableGoods" text="商品已下架" />
        <!-- 操作栏 -->
        <ActionBar :isDisable="isDisableAddress || isDisableGoods" @buyNow="buyNow" @addBag="addBag" />
        <!-- 选择规格 -->
        <ChooseGoods
            ref="choose"
            :info="goodsDetail"
            :isOnlySelect="isOnlySelect"
            :isChangeSku="isChangeSku"
            :isAddBag="isAddBag"
            :isNowBuy="isNowBuy"
            @ensure="ensureChoose"
        />
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { CountDown } from '@components/base';
import { Footer } from '@components/biz';
import Swiper from './detail/Swiper';
import BaseInfo from './detail/BaseInfo';
import SelectArea from './detail/SelectArea';
import PictureAndText from './detail/PictureAndText';
import ActionBar from './detail/ActionBar';
import ShopContainer from './components/ShopContainer';
import GoodsItem from './components/GoodsItem';
import ChooseGoods from './components/ChooseGoods';
import ShopDesc from './special/ShopDesc';
import DetailTip from './detail/DetailTip';
import ActivityInfo from './detail/ActivityInfo';

import { isEmptyObject, redirectTo, setTitle } from '@common/utils';
import { detailToReview } from '@biztools/shopDetail';
import { getUiMode, getUiTheme, getUiStyleMode, getBrandIdCookie, getBrandNameCookie } from '@biztools/info';
import { SHOP_MODE_TYPE } from '@constants/shop';
import { DEFAULT_MODE, DEFAULT_THEME, DEFAULT_STYLE_MODE } from '@constants/style';
import logger from '@common/logger';
import { TipSuccess } from '@common/tip';

export default {
    name: 'CommodityDetail', // 商品详情
    components: {
        Footer,
        Swiper,
        BaseInfo,
        SelectArea,
        PictureAndText,
        ShopContainer,
        GoodsItem,
        ActionBar,
        ShopDesc,
        ChooseGoods,
        DetailTip,
        CountDown,
        ActivityInfo,
    },
    data() {
        return {
            isOnlySelect: true,
            isChangeSku: false,
            isAddBag: false,
            isNowBuy: false,
            isDisableAddress: false,
            // 获取设置的配置信息
            mode: getUiMode() || DEFAULT_MODE,
            theme: getUiTheme() || DEFAULT_THEME,
            styleMode: getUiStyleMode() || DEFAULT_STYLE_MODE,
        };
    },
    computed: {
        ...mapState({
            goodsDetail: state => state.detail.goodsDetail,
            selectSkuInfo: state => state.detail.selectSkuInfo,
            storeInfo: state => state.special.storeInfo,


            // shopIndexLibraryInfo: state => state.shop.shopIndexLibraryInfo,
            // specialShopInfo: state => state.shopSpecial.specialShopInfo,
            // goodsWarehouseInfo: state => state.shopDetail.goodsWarehouseInfo,
            // shopInfoData: state => state.shop.shopInfoData,
            // shopReviewAddress: state => state.shopReview.shopReviewAddress,
            // addressInfo: state => state.shopAddress.addressInfo,
        }),
        isBrandMode() {
            return this.shopInfoData.operation_mode === SHOP_MODE_TYPE.brand;
        },
        isDisableGoods() {
            return this.goodsDetail.status === 0;
        },
    },
    async created() {
        setTitle('商品详情');
        const { goodsId } = this.$route.params;
        const { storeId} = this.$route.query;
        if (storeId) {
            this.setStoreInfo(storeId);
        } else {
            this.setStoreInfo(null);
        }
        // 获取商品信息
        await this.getGoodsDetailInfo(goodsId);
        await this.getOnlineShopCartData();
        await this.getGoodsDiscountInfo(goodsId);
        this.setSelectSkuInfo(null);
        // let param = {
        //     addressInfo: this.shopReviewAddress || this.addressInfo,
        //     isMain: this.isBrandMode,
        // };
        // if (this.specialShopInfo && this.specialShopInfo.id !== 0) {
        //     param = {
        //         ...param,
        //         storeId: this.specialShopInfo.isMainWarehouseInfo ? 0 : this.specialShopInfo.id,
        //     };
        // }
        // await this.matchGoodsWarehouse(param);
        // if (this.goodsWarehouseInfo || (this.specialShopInfo && this.specialShopInfo.id !== 0)) {
        //     this.isDisableAddress = false;
        //     const _param = this.getSkuInfoParams();
        //     logger.debugger('Detail => _param', _param);
        //     await this.getGoodsSkusInfo(_param);
        // } else {
        //     this.isDisableAddress = true;
        // }
    },
    watch: {
        async shopReviewAddress(val, oldVal) {
            // 修改当前的详情的仓库信息
            await this.refreshGoodsDetailInfo(val);
        },
    },
    methods: {
        ...mapActions([
            'getGoodsDetailInfo',
            'getGoodsDiscountInfo',
            'getOnlineShopCartData',
            'setOrderReviewList',
            'setStoreInfo',
            'setSelectSkuInfo',
            'addShopBagItem',

            // 'getGoodsInfo',
            // 'getGoodsPropsInfo',
            // 'getGoodsSkusInfo',
            // 'setSelectSkuInfo',
            // 'changeShopReviewList',
            // 'changeInvalidReviewList',
            // 'matchGoodsWarehouse',
        ]),
        openCouponActivity() {
            this.$refs.couponAndActivity.show();
        },
        getSkuInfoParams() {
            // 先判断运营模式
            // 在判断是否是总部自营的仓库信息（store_id == 0）
            // 再判断是否是总部仓
            logger.debugger('Detail => specialShopInfo', this.specialShopInfo);
            if (this.isBrandMode) {
                return {
                    warehouseId: this.goodsWarehouseInfo && this.goodsWarehouseInfo.id || 0,
                    storeId: this.specialShopInfo && this.specialShopInfo.id || 0,
                };
            } else {
                if (this.specialShopInfo.store_id === 0) {
                    return {
                        warehouseId: this.goodsWarehouseInfo && this.goodsWarehouseInfo.id || 0,
                    };
                } else {
                    return this.specialShopInfo.isMainWarehouseInfo ? {
                        warehouseId: this.specialShopInfo && this.specialShopInfo.id || 0,
                    } : {
                        warehouseId: this.goodsWarehouseInfo && this.goodsWarehouseInfo.id || 0,
                        storeId: this.specialShopInfo && this.specialShopInfo.id || 0,
                    };
                }
            }
        },
        // 刷新商品库存等信息，重新匹配仓库
        async refreshGoodsDetailInfo(addressInfo) {
            // 修改当前的详情的仓库信息
            await this.matchGoodsWarehouse(addressInfo);
            console.log('当前的仓库信息为', this.goodsWarehouseInfo);
            const _param = this.getSkuInfoParams();
            logger.debugger('Detail => _param', _param);
            // 总部模式
            await this.getGoodsSkusInfo(_param);
        },
        changeSelectType(type) {
            this.isOnlySelect = false;
            this.isChangeSku = false;
            this.isAddBag = false;
            this.isNowBuy = false;
            switch(type) {
            case 'bag':
                this.isAddBag = true;
                break;
            case 'now':
                this.isNowBuy = true;
                break;
            default:
                this.isOnlySelect = true;
                break;
            }
        },
        selectSku() {
            if (!this.isDisableGoods) {
                this.$refs.choose.show();
            }
        },
        // 加入购物车操作
        async addBag() {
            if (this.selectSkuInfo) {
                // 将当前规格加入购物车，并清空选中的规格
                // 添加到购物袋
                const item = {
                    prod_id: this.goodsDetail.id,
                    sku_id: this.selectSkuInfo.id,
                    quantity: this.selectSkuInfo.quantity,
                    store_id: 0,
                    store_name: getBrandNameCookie(),
                };
                const flag = await this.addShopBagItem(item);
                if (flag) {
                    this.setSelectSkuInfo(null);
                    TipSuccess('加入购物车成功');
                }
            } else {
                this.changeSelectType('bag');
                // 打开选择弹框
                this.selectSku();
            }
        },
        // 立即购买操作
        buyNow() {
            logger.info('Detail => 立即购买', this.selectSkuInfo);
            // 判断是否是已经选择规格
            // 是-直接进入review界面
            // 不是-打开选择规格弹框
            if (this.selectSkuInfo) {
                this.gotoReview(this.selectSkuInfo);
            } else {
                this.changeSelectType('now');
                this.selectSku();
            }
        },
        async ensureChoose(skuInfo) {
            logger.debugger('选择的规格详情为：', skuInfo);
            if (this.isOnlySelect) {
                this.setSelectSkuInfo(skuInfo);
            }
            // 确认选择，直接购买
            if (this.isAddBag) {
                // 添加到购物袋
                const item = {
                    prod_id: this.goodsDetail.id,
                    sku_id: skuInfo.id,
                    quantity: skuInfo.quantity,
                    store_id: 0,
                    store_name: getBrandNameCookie(),
                };
                const flag = await this.addShopBagItem(item);
                flag && TipSuccess('加入购物车成功');
            }
            if (this.isNowBuy) {
                this.gotoReview(skuInfo);
            }
            // reset
            this.changeSelectType();
        },
        gotoReview(skuInfo) {
            const reviewList = detailToReview(this.goodsDetail, skuInfo, this.storeInfo);
            logger.info('ShopDetail => 生成的review数据为：', reviewList);
            this.setOrderReviewList(reviewList);
            // this.changeInvalidReviewList([]);
            redirectTo('shop/review');
        },
    },
};
</script>

<style lang="less">
.tech-commodity-detail {
    .mode-white();
    &.white {
        background-color: @shop-bg-color;
    }
    &.black {
        background-color: @black !important;
    }
    .shop-column {
        .container-content {
            .p-l(@shop-gap-md);
        }
    }
    .shop-info-container {
        background-color: @white;
        .m-v(@shop-gap-md);
    }
}
</style>
